
from django_redis import get_redis_connection
import json,pickle,base64
from django.shortcuts import render
from django.views import View
from django import http
from redis.utils import pipeline


from goods.models import SKU
from meiduo_mall.utils.response_code import RETCODE


class CartsView(View):
    def post(self, request):
        """添加购物车"""
        # 接受参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)
        # 校验参数
        # 判断参数有没有传
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id 是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断是否是登陆用户
        user = request.user
        if user.is_authenticated:
            # 登陆用户建立redis连接
            #创建连接
            redis_conn = get_redis_connection('carts')
            # 创建管道
            pl = redis_conn.pipeline()
            # 新增购物车数据（hash， set）
            pl.hincrby('carts_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            # 执行管道
            pl.execute()
            # 响应
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
        else:
            # 未登陆用户把数据存在cookie
            cart_str = request.COOKIES.get('carts')
            # 如国用户操作过购物车
            if cart_str:
                # 将cart_str转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
                # 判断本次商品有没有被添加，有就累加
                if sku_id in cart_dict:
                    # 累加
                    origin_count = cart_dict[sku_id]['count']
                    count += origin_count
            else:
                # 用户没有操作过cookie购物车
                cart_dict = {}
            cart_dict[sku_id] = {
                'count':count,
                'selected': selected
            }
            # 将字典转成字符串
            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
            # 创建响应对象
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
            response.set_cookie('carts', cookie_cart_str)
            return response

    def get(self, request):
        """展示购物车"""
        # 判断用户是否登陆
        user = request.user
        if user.is_authenticated:
            # 登陆了就用redis的数据
            # 创建redis连接对象
            redis_conn = get_redis_connection('carts')
            # 获取redis里面的两个数据
            redis_carts = redis_conn.hgetall('carts_%s' % user.id)
            redis_selected = redis_conn.smembers('selected_%s' % user.id)
            # 将redis数据构造成跟cookie的一样，方便统一查询
            cart_dict = {}
            for sku_id_count in redis_carts:
                cart_dict[int(sku_id_count)] = {
                    'count': int(redis_carts[sku_id_count]),
                    'selected': sku_id_count in redis_selected
                }

        else:
            # 没登陆就用cookie的值
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将字典转码
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                # 如果没有购物车数据，直接显示购物车
                return render(request, 'cart.html')
        # 都统一渲染数据
        sku_qs = SKU.objects.filter(id__in=cart_dict.keys())
        cart_skus = []
        for sku in sku_qs:
            count = cart_dict[sku.id]['count']
            cart_skus.append({
                'id':sku.id,
                'name':sku.name,
                'count':count,
                'selected': str(cart_dict[sku.id]['selected']),
                'default_image_url':sku.default_image.url,
                'price':str(sku.price),
                'amount':str(sku.price * count),
            })
        context = {
            'cart_skus': cart_skus
        }
        return render(request, 'cart.html', context)

    def put(self, request):
        # 接受参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)
        # 校验参数
        # 判断参数有没有传
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id 是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断是否是登陆用户
        user = request.user
        if user.is_authenticated:
            # 登陆用户建立redis连接
            #创建连接
            redis_conn = get_redis_connection('carts')
            # 创建管道
            pl = redis_conn.pipeline()
            # 修改redis的数据
            pl.hset('count_%s' % user.id, sku_id, count)
            # 是否选中
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()

            # 创建响应对象
            sku = SKU.objects.get(id=sku_id)
            cart_sku = ({
                'id':sku.id,
                'name':sku.name,
                'count':count,
                'selected': selected,
                'default_image_url':sku.default_image.url,
                'price':str(sku.price),
                'amount':str(sku.price * count),
            })
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改成功', 'cart_sku': cart_sku})
        else:
            # 是没登陆的用户
            # 操作cookie的数据
            cart_str = request.COOKIES.get('carts')
            # 判断有没有获取到
            if cart_str:
                # 如果有就转化成字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                return render(request, 'cart.html')
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            # 把字典再转换成字符串
            cookie_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 创建响应对象
            sku = SKU.objects.get(id=sku_id)
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            response = http.JsonResponse({'code': RETCODE.OK, "errmsg": '修改购物车成功', 'cart_sku': cart_sku})
            # 重新写如cookie
            response.set_cookie('carts', cart_str)
            return response

    def delete(self, request):
        # 接收请求体中的sku_id
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        # 校验
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('sku_id不存在')
        user = request.user
        # 判断用户有没有登陆
        if user.is_authenticated:
            # 登陆用户删除redis
            # 创建redis连接
            redis_conn = get_redis_connection('carts')
            # 创建管道
            pl = redis_conn.pipeline()
            # 删除count和selected从redis里
            pl.hdel('carts_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id, sku_id)
            # 执行管道
            pl.execute()
            # 响应
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除成功'})
        else:
            # 未登陆用户删除cookie
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 把字符串转花为字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                return render(request, 'cart.html')
            if sku_id in cart_dict:
                del cart_dict[sku_id]
            response = http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '删除成功'})
            if not cart_dict:
                response.delete_cookie('carts')
                return response
            cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
            response.set_cookie('carts', cart_str)
            return response

class CartsSelectAllView(View):
    """全选购物车"""
    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        user = request.user
        if user.is_authenticated:
            # 创建连接对象
            redis_conn = get_redis_connection('carts')

            if selected:
                # 全选
                # 先获取hash所有数据
                cart = redis_conn.hgetall('carts_%s' % user.id)
                sku_ids = redis_conn.keys()
                # 将购物车中所有sku——id添加到购物车
                redis_conn.sadd('selected_%s' % user.id, *sku_ids)

            else:
                redis_conn.delete('selected_%s' % user.id)
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
        else:
            # 操作cookies
            # 获取cookies
            cart_str = request.COOKIES.get('carts')
            # 判断是否有cookies购物车shuju
            if cart_str:
                # 有就转字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
            # 没有就响应
                return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '参数无效'})
            # 修改字典里面的valtue的值为false或ture
            for sku_id in cart_dict:
                cart_dict[sku_id] = {
                    'count': cart_dict[sku_id]['count'],
                    'selected': selected
                }
            # 转字典成字符串
            cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
            # 创建响应对象
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
            response.set_cookie('carts', cart_str)
            return response


class CartsSimpleView(View):
    """简单版购物车"""
    def get(self, request):
        """展示购物车"""
        # 判断用户是否登陆
        user = request.user
        if user.is_authenticated:
            # 登陆了就用redis的数据
            # 创建redis连接对象
            redis_conn = get_redis_connection('carts')
            # 获取redis里面的两个数据
            redis_carts = redis_conn.hgetall('carts_%s' % user.id)
            redis_selected = redis_conn.smembers('selected_%s' % user.id)
            # 将redis数据构造成跟cookie的一样，方便统一查询
            cart_dict = {}
            for sku_id_count in redis_carts:
                cart_dict[int(sku_id_count)] = {
                    'count': int(redis_carts[sku_id_count]),
                    'selected': sku_id_count in redis_selected
                }

        else:
            # 没登陆就用cookie的值
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将字典转码
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                # 如果没有购物车数据，直接显示购物车
                return render(request, 'cart.html')
        # 都统一渲染数据
        sku_qs = SKU.objects.filter(id__in=cart_dict.keys())
        cart_skus = []
        for sku in sku_qs:
            count = cart_dict[sku.id]['count']
            cart_skus.append({
                'id':sku.id,
                'name':sku.name,
                'count':count,
                'default_image_url':sku.default_image.url,
            })

        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'OK', 'cart_skus':cart_skus})
